package com.broada.apm.indicator.api.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.broada.apm.dao.FilterDao;
import com.broada.apm.dao.SettingDao;
import com.broada.apm.indicator.api.ConfigItemService;
import com.broada.apm.model.ConfigItem;
import com.broada.apm.model.Filter;
import com.broada.apm.model.FilterRule;

public class ConfigItemServiceImpl implements ConfigItemService {

	@Autowired
	private SettingDao settingDao;
	
	@Autowired
	private FilterDao filterDao;
	
	@Override
	public void saveConfigItem(ConfigItem configItem) {
		ConfigItem exist = settingDao.getSetting(configItem.getKey());
		if (exist == null)
			settingDao.addSetting(configItem);
		else
			settingDao.updateSetting(configItem);
	}

	@Override
	public void updateConfigItem(ConfigItem configItem) {
		settingDao.updateSetting(configItem);
	}

	@Override
	public ConfigItem deleteConfigItem(String key) {
		ConfigItem configItem = settingDao.getSetting(key);
		settingDao.deleteSetting(configItem);
		return configItem;
	}

	@Override
	public ConfigItem getConfigItem(String key) {
		return settingDao.getSetting(key);
	}

	@Override
	public List<ConfigItem> getConfigItemLikeKey(String key) {
		return settingDao.getSettingLikeKey(key);
	}
	
	@Override
	public void saveFilter(List<Filter> filterList) {
		Filter first = filterList.get(0);
		filterDao.truncateFilter(first.getAnalyzerId());    // 修改为delete相关协议分析器过滤的数据
		if(StringUtils.isBlank(first.getDstFromIp())
		   && StringUtils.isBlank(first.getDstFromPort())
		   && StringUtils.isBlank(first.getDstToIp())
		   && StringUtils.isBlank(first.getDstToPort())
		   && StringUtils.isBlank(first.getSrcFromIp())
		   && StringUtils.isBlank(first.getSrcFromPort())
		   && StringUtils.isBlank(first.getSrcToIp())
		   && StringUtils.isBlank(first.getSrcToPort())){
			return ;
		}
		for (Filter filter : filterList){
			filterDao.addFilter(filter);
		}
	}
	
	@Override
	public List<Filter> getAllFilters(String analyzerId) {
		return filterDao.getAllFilters(analyzerId);
	}
	
	@Override
	public List<FilterRule> getAllFiltersJson(String analyzerId) {
		return filterDao.getAllFiltersJson(analyzerId);
	}

	@Override
	public void deleteFilter(String analyzerId) {
		filterDao.truncateFilter(analyzerId);
	}
	
	@Override
	public void deleteFilterById(String id) {
		filterDao.truncateFilterById(id);
	}

	@Override
	public void saveFilter(Filter filter) {
		filterDao.addFilter(filter);
	}
}
